import {Button, message, Modal, Table, Tag} from 'antd';
import React from 'react';
import DataCategory from '../../types/DataCategory';
import {getRes} from '../../configFile';
import {listDataCategory, queryCategoryAmount} from '../../requests/DataCategory';
import './DataCatogoryForDevice.less'

interface IProps {
    setSelectedCate: (arr: Array<DataCategory>) => void
    propCate: DataCategory[]
}
interface IState {
    DataCategorySource: Array<DataCategory & { key: number }>
    addedDataCategory: Array<DataCategory>
    amount: number
    offset: number
    limit: number
    visible: boolean
}
export default class DataCategoryForDevice extends React.Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            addedDataCategory: this.props.propCate,
            DataCategorySource: [],
            amount: 0,
            offset: 0,
            limit: 5,
            visible: false
        }
    }
    //获取数据类型数据
    getDataCategory = async () => {
        try {
            const amountRes = getRes(await queryCategoryAmount())
            if (amountRes.isSuccessful === false) {
                message.error(amountRes.message)
                return;
            }
            const res = getRes(await listDataCategory(this.state.offset, this.state.limit))
            if (res.isSuccessful === false) {
                message.error(res.message)
                return;
            }
            this.setState({
                DataCategorySource: res.data.map((item: DataCategory) => Object.assign({}, item, { key: item.dataCategoryID })),
                amount: amountRes.data
            })
        }
        catch (error) {
            message.error(error.toString())
        }
    }

    async componentDidMount() {
        this.getDataCategory()
    }
    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    handleOk = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
        if (!!this.state.addedDataCategory)
            this.props.setSelectedCate(this.state.addedDataCategory)
        this.setState({
            visible: false,
        });
    };

    handleCancel = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
        this.setState({
            addedDataCategory: this.props.propCate,
            visible: false,
        });
    };

    //是否允许添加新的数据类型
    ifAbleToAdd = (item: DataCategory) => {
        //已有这个id的数据类型
        if (this.state.addedDataCategory.map(item => item.dataCategoryID).includes(item.dataCategoryID)) {
            return false;
        }
        return true;
    }

    //选中新的数据类型
    addSelectedCate = (item: DataCategory & { key: number }) => {
        //允许添加
        if (this.ifAbleToAdd(item)) {
            this.state.addedDataCategory.push(item);
        }
        this.setState({
            ...this.state
        })
    }
    //删除已选中数据类型
    deleteAdded = (item: DataCategory) => {
        this.setState({
            addedDataCategory: this.state.addedDataCategory.filter(addedItem => addedItem.dataCategoryID !== item.dataCategoryID)
        })
    }
    //表格展示的列
    columns = [{
        title: '数据类型名',
        dataIndex: 'dataCategoryName',
        key: 'dataCategoryName',
    },
    {
        title: '数据类型',
        dataIndex: 'dataType',
        key: 'dataType',
    },
    {
        title: '操作',
        key: 'action',
        render: (record: DataCategory & { key: number }) => (
            <Button size='middle' onClick={this.addSelectedCate.bind(this, record)}>添加</Button>
        )
    }]
    render() {
        return (
            <>
                <Button type="primary" onClick={this.showModal}>
                    添加数据
                </Button>
                <Modal
                    width="800px"
                    title="添加数据"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <div className="addedCatogoryForDevice" style={this.state.addedDataCategory.length === 0 ?
                        { display: 'none' }
                        :
                        {}}
                    >
                        已添加数据:{
                            !!this.state.addedDataCategory ? (this.state.addedDataCategory.map(item => {
                                return (
                                    <Tag style={{ margin: 8 }}
                                        closable
                                        key={item.dataCategoryID}
                                        onClose={() => this.deleteAdded(item)}
                                    >
                                        {item.dataCategoryName}
                                    </Tag>)
                            })) : ''
                        }
                    </div>
                    <Table columns={this.columns}
                        dataSource={this.state.DataCategorySource}
                        pagination={{
                            onChange: (page, pageSize) => {
                                if (!!pageSize) {
                                    this.setState({
                                        offset: (page - 1) * (pageSize),
                                        limit: (pageSize)
                                    },()=>{
                                        this.getDataCategory()
                                    })
                                }
                            },
                            defaultPageSize: this.state.limit,
                            total: this.state.amount,
                            showSizeChanger: false
                        }} />
                </Modal>
            </>
        );
    }
}